#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import json
import requests
import traceback

sys.path.append(
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "imlfapi")
)

from db import WindFarmInfoTB, EntityTB

# 测试
base_url = "http://localhost:8000/imlf/api/v1/"
# 线上
# base_url = 'http://10.12.3.162:32488/imlf/api/v1/'
headers = {
    "token": "",
}


def add_entity_by_api(datas):
    url = base_url + "entites"
    for num, data in enumerate(datas):
        print("增加 %s / %s" % (num, len(datas)))
        data = dict(
            username=data["username"], bizId=data["biz_id"], bizType=data["biz_type"]
        )
        res = requests.post(url, headers=headers, json=data)
        content = json.loads(res.content)
        print(content)


def delete_entity_by_api(ids):
    for num, id in enumerate(ids):
        print("删除 %s / %s" % (num, len(ids)))
        url = base_url + "entites/%s" % id
        res = requests.delete(url, headers=headers)
        content = json.loads(res.content)
        print(content)


def insert_batch(db, table, datas, num=2000):
    """
    批量插入
    """
    try:
        cnt = 0
        while len(datas) > cnt:
            ceil_list = datas[cnt: cnt + num]
            db.insert_list(table, ceil_list)
            cnt += num
    except Exception:
        print(traceback.format_exc())
        raise ValueError("插入数据失败")


def main():
    # 从WindFarmdb wind_farm_info取所有用户列表数据
    users = (
        WindFarmInfoTB.select().fields("administrator").group_by("administrator").all()
    )
    for user in users:
        if user["administrator"]:
            windfarm_wfid = []
            imlf_wfid = []
            # 从WindFarmdb wind_farm_info取wfid数据
            windfarm_wfid = (
                WindFarmInfoTB.select()
                .fields("wfid")
                .where(administrator=user["administrator"])
                .all()
            )
            # 从imlf实体entity表中取出已有wfid
            imlf_wfid = (
                EntityTB.select()
                .fields("id, biz_id")
                .where(username=user["administrator"])
                .all()
            )
            windfarm_wfid_set = set([i["wfid"] for i in windfarm_wfid])
            imlf_wfid_set = set([i["biz_id"] for i in imlf_wfid])
            # 计算差值
            diff_wfid_set = windfarm_wfid_set - imlf_wfid_set
            # 插入增加的wfid
            add_entity_datas = []
            for i in diff_wfid_set:
                data = {
                    "username": user["administrator"],
                    "biz_id": i,
                    "biz_type": "wfid",
                    "status": 1,
                }
                add_entity_datas.append(data)
            delete_set = imlf_wfid_set-windfarm_wfid_set
            imlf_wfid2id_map = {i['biz_id']: i['id'] for i in imlf_wfid}
            delete_ids = [imlf_wfid2id_map[i] for i in delete_set]
            # print(len(delete_ids))
            # print(len(add_entity_datas))
            # print(delete_ids)
            # print(add_entity_datas)
            delete_entity_by_api(delete_ids)
            add_entity_by_api(add_entity_datas)


if __name__ == "__main__":
    main()
